package com.sa07.user.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.sa07.bean.Role;
import com.sa07.bean.User;
import com.sa07.db.Session;
import com.sa07.db.dao.H2BaseDao;
import com.sa07.exception.DatabaseExecuteFailedException;

/**
 * 用户Dao
 * 
 * @author Long.shangbo
 *
 * 2014-2-21 下午2:51:09
 */
public class UserDao extends H2BaseDao implements IUserDao{
	
	/**
	 * 查询所有用户
	 * @return
	 * @throws DatabaseExecuteFailedException 
	 */
	public List<User> queryAllUser() throws DatabaseExecuteFailedException{
		Session session = createSession();
		String sql = "select u.user_id, u.user_name from so_user u";
		ResultSet rs = session.executeQuery(sql, new Object[]{});
		
		List<User> userList = new ArrayList<User>();
		User user = null;
		
		try {
			while(rs.next()){
				user = new User();
				user.setUserId(rs.getInt(1));
				user.setUserName(rs.getString(2));
				userList.add(user);
			}
		} catch (SQLException e) {
			e.printStackTrace();
			logger.error("Query user failed, caused by -> " + e);
			throw new DatabaseExecuteFailedException(e);
		} finally{
			session.close();
		}
		
		return userList;
		
	}

	@Override
	public User login(int userId, int roleId, String userPwd) throws DatabaseExecuteFailedException {
		Session session = createSession();
		String sql = "select u.user_id, u.user_name, u.user_password, u.role_id, r.role_name " +
				"from so_user u INNER JOIN so_role r on u.role_id = r.role_id " +
				"WHERE u.user_id = " + userId + " and u.role_id = " + roleId;
		ResultSet rs = session.executeQuery(sql, new Object[]{});
		User user = null;
		Role role = null;
		
		try {
			if(rs.next()){
				user = new User();
				user.setUserId(rs.getInt(1));
				user.setUserName(rs.getString(2));
				user.setPassword(rs.getString(3));
				
				role = new Role();
				role.setRoleId(rs.getInt(4));
				role.setRoleName(rs.getString(5));
				user.setRole(role);
			}
		} catch (SQLException e) {
			e.printStackTrace();
			logger.error("Query user information failed, caused by -> " + e);
			throw new DatabaseExecuteFailedException(e);
		} finally{
			session.close();
		}
		
		return user;
	}
}
